package com.tanhua.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.manager.constant.CacheKey;
import com.tanhua.manager.domain.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头 Authorization
        String authorization = request.getHeader("Authorization");
        if (authorization==null){
            response.setStatus(401);
            return false;
        }
        //2.从中得到token
        String token = authorization.replace("Bearer ", "");

        //3.从redis中获取当前用户
        String adminJson = redisTemplate.opsForValue().get(CacheKey.TOKEN_PREFIX + token);
        if (adminJson==null){
            response.setStatus(401);
            return false;
        }
        //4.把当前用户和token绑定当前线程
        Admin admin = JSON.parseObject(adminJson, Admin.class);
        AdminHolder.setAdmin(admin);
        AdminHolder.setToken(token);
        return  true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
     AdminHolder.removeAdmin();;
     AdminHolder.removeToken();
    }
}
